from django.shortcuts import render
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.response import Response
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


# Create your views here.
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthUserSerializer


class QQAuthURLView(APIView):

    def get(self, request):
        # 获取state
        state = request.query_params.get('state', None)

        if not state:
            state = '/'

        # qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 调用qq对象生成跳转连接
        login_url = qq.get_qq_url()

        # 返回跳转连接
        return Response({'login_url': login_url})


class QQAuthUserView(CreateAPIView):

    serializer_class =QQAuthUserSerializer

    def get(self,reqeust):

        # 获取code数据
        code=reqeust.query_params.get('code',None)

        # 判断code数据钱是否传递过来
        if code is None:
            return Response({'errors':'缺少code值'},status=400)

        # qq对象
        state='/'
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 通过code值请求qq服务器获取access_token值

        access_token=qq.get_access_token(code)

        # 通过access_token值请求qq服务器获取openid值
        openid=qq.get_open_id(access_token)

        # 判断openid值是否绑定过美多用户
        try:
            qq_user=OAuthQQUser.objects.get(openid=openid)
        except:
            # 未绑定，进行绑定操作
            # 对oepnid加密
            tjs=TJS(settings.SECRET_KEY,300)
            open_id=tjs.dumps({'openid':openid}).decode()
            return Response({'openid':open_id})

        else:

            # 已绑定，登录成功
            user=qq_user.user

            # 生成token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )

    # def post(self,request):
    #
    #     # 获取数据
    #
    #     # 验证数据
    #
    #     # 保存数据
    #
    #     # 返回结果


